package com.ruoyi.act.module.api;

import cn.hutool.crypto.digest.MD5;
import com.ruoyi.act.config.annotation.VerifyIgnore;
import com.ruoyi.act.module.domain.ActBizInfo;
import com.ruoyi.act.module.service.IActBizInfoService;
import com.ruoyi.act.module.service.IJJwtService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 工作流租户对象 act_biz_info
 *
 * @author hcj
 * @date 2020-12-24
 */
@RestController
@RequestMapping("/api/tenant")
public class ApiLoginController extends BaseController {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IJJwtService ijJwtService;
    @Autowired
    private IActBizInfoService iActBizInfoService;

    /**
     * 租户登录
     *
     * @param actBizInfo
     * @return
     */
    @PostMapping("/login")
    @VerifyIgnore
    public AjaxResult login(@RequestBody ActBizInfo actBizInfo) {

        if (StringUtils.isBlank(actBizInfo.getPassword())) {
            return AjaxResult.error("认证失败");
        }

        actBizInfo.setPassword(MD5.create().digestHex(actBizInfo.getPassword()));

        ActBizInfo info = iActBizInfoService.selectByUserNameAndPassword(actBizInfo);
        if (null == info) {
            return AjaxResult.error("认证失败");
        }

        if (redisCache.getCacheObject(info.getId()) != null) {
            //TODO 重复登陆直接返回为token
            Map<String, Object> map = new HashMap<>();
            map.put("token", redisCache.getCacheObject(info.getId() + "_token"));
            map.put("tenantId", info.getId());
            return AjaxResult.success(map);
        }

        String token = ijJwtService.createToken(info);

        redisCache.setCacheObject(info.getId() + "_token", token);

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("tenantId", info.getId());

        return AjaxResult.success(map);
    }
}
